<template>
  <div class="app-container cyberpunk-theme">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" class="cyber-form">
      <el-form-item label="账号" prop="zh">
        <el-input v-model="queryParams.zh" placeholder="请输入账号" clearable style="width: 150px"
                  @keyup.enter="handleQuery" class="cyber-input"/>
      </el-form-item>
      <el-form-item label="游戏昵称" prop="wgname">
        <el-input v-model="queryParams.wgname" placeholder="请输入游戏昵称" clearable style="width: 150px"
                  @keyup.enter="handleQuery" class="cyber-input"/>
      </el-form-item>
      <el-form-item label="货架" prop="hid">
        <el-input v-model="queryParams.hid" placeholder="请输入货架" clearable style="width: 150px"
                  @keyup.enter="handleQuery" class="cyber-input"/>
      </el-form-item>
      <el-form-item label="货架类型" prop="htype">
        <el-select
            v-model="queryParams.htype"
            placeholder="货架类型"
            style="width: 150px"
            @change="handleQuery"
        >
          <el-option
              v-for="dict in bh_htype"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="货架状态" prop="hstatus">
        <el-select
            v-model="queryParams.hstatus"
            placeholder="货架状态"
            clearable
            style="width: 150px"
            @change="handleQuery"
        >
          <el-option
              v-for="dict in bh_allstatus"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery" class="cyber-button">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery" class="cyber-button secondary">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8 cyber-actions">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Top" :disabled="multiple" @click="handleOnShelfList"
                   v-hasPermi="['custom:bh:basic']" class="cyber-button action">批量上架
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Bottom" :disabled="multiple" @click="handleOffShelfList"
                   v-hasPermi="['custom:bh:basic']" class="cyber-button action">批量下架
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Edit" :disabled="multiple" @click="changePriceList"
                   v-hasPermi="['custom:bh:basic']" class="cyber-button action">批量改价
        </el-button>
      </el-col>
      <right-toolbar-store v-model:showSearch="showSearch" @queryTable="getList"
                           v-model:columns="columns"></right-toolbar-store>
    </el-row>

    <TableContextMenu
        :menu-items="customMenuItems"
        @menu-action="handleMenuAction"
        @row-selected="handleRowSelected"
    >
      <template #table="{ handleRowContextMenu, currentRow,disableExpandRowContext }">
        <el-table stripe
                  empty-text="暂无数据，首次登录需要等待1-2分钟系统初始化数据"
                  row-key="zh"
                  :data="tableData"
                  ref="tableRef"
                  @selection-change="handleSelectionChange"
                  @expand-change="handleExpandChange"
                  style="width: 100%"
                  @row-contextmenu="(row, column, event) => handleRowContextMenu(row, event)"
                  :row-class-name="(row) => tableRowClassName(row, currentRow)"
                  class="cyber-table"
        >
          <el-table-column type="expand" width="40">
            <template #default="scope">
              <div
                  style="display: flex; flex-wrap: wrap; gap: 16px; padding: 8px 20px;background: #f8fafc; border-radius: 8px;"
                  @contextmenu="disableExpandRowContext" class="cyber-expand">
                <div style="flex: 1; min-width: 200px;">
                  <p>最后刷新时间</p>
                  <p>货架信息: {{ parseTime(scope.row.hjstatus_time) }}</p>
                  <p>二级密码: {{ parseTime(scope.row.ejpwd_time) }}</p>
                </div>
                <div style="flex: 1; min-width: 300px;">
                  <p>装备信息: {{ parseTime(scope.row.zb_time) }}</p>
                  <p>禁玩状态: {{ parseTime(scope.row.jwstatus_time) }}</p>
                  <p>营地状态: {{ parseTime(scope.row.ydstatus_time) }}</p>
                </div>
                <div style="flex: 1; min-width: 300px;">
                  <p>租号玩备注: {{ parsedJson(scope.row.zh_cfg)?.zhwRemark }}</p>
                  <p>转转备注: {{ parsedJson(scope.row.zh_cfg)?.zzRemark }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="30" align="center" reserve-selection/>
          <el-table-column label="监控" align="center" width="65" prop="off_on">
            <template #default="scope">
              <el-switch
                  v-model="scope.row.off_on"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleStatusChange(scope.row)"
                  class="cyber-switch"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="游戏账号" align="center" prop="zh" width="120" :show-overflow-tooltip="true" fixed>
            <!--fixed -->
            <template #header>
              <div>游戏账号</div>
              <div class="table-subtitle">游戏昵称</div>
            </template>
            <template #default="scope">
              <div>{{ scope.row.zh }}</div>
              <div class="table-subtitle">{{ scope.row.wgname }}</div>
            </template>
          </el-table-column>
          <el-table-column label="区服" align="center" prop="ser" width="90" :show-overflow-tooltip="true">
            <template #header>
              <div>区服</div>
              <div class="table-subtitle">二级密码</div>
            </template>
            <template #default="scope">
              <div>{{ scope.row.ser }}</div>
              <div>
                <dict-tag :options="bh_erjpwd" :value="scope.row.erjpwd" class="cyber-tag"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="营地状态" align="center" width="90" prop="ydstatus">
            <template #header>
              <div>营地状态</div>
              <div class="table-subtitle">禁玩状态</div>
            </template>
            <template #default="scope">
              <div>
                <dict-tag :options="bh_ydstatus" :value="scope.row.ydstatus" class="cyber-tag"/>
              </div>
              <div>
                <dict-tag :options="bh_jwstatus" :value="scope.row.jwstatus" class="cyber-tag"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="装备简述" align="left" prop="zbShort" width="110" :show-overflow-tooltip="true">
            <template #default="scope">
              <div class="equip-item pink">粉:{{
                  parsedJson(scope.row.zb_short)?.pinkSuitNum
                }}；枪:{{ parsedJson(scope.row.zb_short)?.pinkGunNum }}
              </div>
              <div class="equip-item red">载:{{
                  parsedJson(scope.row.zb_short)?.vehicleNum
                }}；红:{{ parsedJson(scope.row.zb_short)?.redOutfitNum }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="150" v-if="columns[0].visible" :show-overflow-tooltip="true">
            <template #header>
              <div class="platform-header">租号玩</div>
            </template>
            <template #default="scope">
              <div v-if="!isStrEmpty(scope.row.zhw_hid)" class="platform-info">
                <div>货架：{{ scope.row.zhw_hid }}</div>
                <div class="platform-details">
                  <dict-tag :options="bh_zhw_zt" :value="scope.row.zhw_zt" class="cyber-tag"/>
                  <div class="platform-price">{{ scope.row.zhw_money }}/小时</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="150" v-if="columns[1].visible" :show-overflow-tooltip="true">
            <template #header>
              <div class="platform-header">U号租</div>
            </template>
            <template #default="scope">
              <div v-if="!isStrEmpty(scope.row.uhz_hid)" class="platform-info">
                <div>货架：{{ scope.row.uhz_hid }}</div>
                <div class="platform-details">
                  <dict-tag :options="bh_uhz_zt" :value="scope.row.uhz_zt" class="cyber-tag"/>
                  <div class="platform-price">{{ scope.row.uhz_money }}/小时</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" width="170" v-if="columns[2].visible" :show-overflow-tooltip="true">
            <template #header>
              <div class="platform-header">转转</div>
            </template>
            <template #default="scope">
              <div v-if="!isStrEmpty(scope.row.zz_hid)" class="platform-info">
                <div>{{ scope.row.zz_hid }}</div>
                <div class="platform-details">
                  <dict-tag :options="bh_zz_zt" :value="scope.row.zz_zt" class="cyber-tag"/>
                  <div class="platform-price">{{ scope.row.zz_money }}/小时</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="错误描述" width="150" align="left" prop="fhremark"/>
          <el-table-column label="排序" align="center" width="56" prop="usort">
            <template #default="{ row, $index }">
              <div v-if="editingRowZh === row.zh">
                <el-input-number v-model="row.usort" style="width: 68px;" :min="0" :max="999" size="small"
                                 controls-position="right"/>
              </div>
              <span v-else>{{ row.usort }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户备注" align="left" prop="remark" :show-overflow-tooltip="true">
            <template #default="{ row, $index }">
              <div class="remark-container">
                <!-- 编辑按钮（右上角） -->
                <div class="edit-buttons" v-if="editingRowZh === row.zh">
                  <el-button
                      link
                      v-hasPermi="['custom:bh:basic']"
                      icon="Select"
                      type="success"
                      size="small"
                      @click="saveEditing(row)"
                      class="cyber-button-icon"
                  >
                    保存
                  </el-button>
                  <el-button
                      link
                      v-hasPermi="['custom:bh:basic']"
                      type="info"
                      icon="CloseBold"
                      size="small"
                      @click="cancelEditing"
                      class="cyber-button-icon"
                  >
                    取消
                  </el-button>
                </div>

                <div v-if="editingRowZh === row.zh">
                  <el-input type="textarea" :rows="2" v-model="row.remark" size="small"/>
                </div>
                <span v-else>{{ row.remark }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </TableContextMenu>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        class="hpjy-pagination-container"
    />

    <!-- 添加或修改自动生成对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body class="cyber-dialog">
      <el-form ref="cinfoForm" :model="form" :rules="rules" label-width="80px" class="cyber-form">
        <el-row v-if="form.channel!=1">
          <el-col :span="12">
            <el-form-item label="起租时长" prop="zz.minTime">
              <el-input-number :min="1" v-model="form.zz.minTime"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-text type="info" class="el-remark-text">无效：租号玩</el-text>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="时租价格" prop="zz.hourPrice">
              <el-input-number :min="0.1" v-model="form.zz.hourPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="success" @click="autoCalcPrice" class="cyber-button calc">自动计算</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="天租价格" prop="zz.dayPrice">
              <el-input-number :min="0.1" v-model="form.zz.dayPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-text type="info" class="el-remark-text"></el-text>
          </el-col>
        </el-row>
        <el-row v-if="form.channel!=3">
          <el-col :span="12">
            <el-form-item label="包早价格" prop="zz.morningPrice">
              <el-input-number :min="0.1" v-model="form.zz.morningPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-text type="info" class="el-remark-text">无效：转转</el-text>
          </el-col>
        </el-row>
        <el-row v-if="form.channel!=3">
          <el-col :span="12">
            <el-form-item label="包午价格" prop="zz.afternoonPrice">
              <el-input-number :min="0.1" v-model="form.zz.afternoonPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-text type="info" class="el-remark-text">无效：转转</el-text>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="包夜价格" prop="zz.oneNightPrice">
              <el-input-number :min="0.1" v-model="form.zz.oneNightPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-text type="info" class="el-remark-text"></el-text>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="十时价格" prop="zz.tenHourPrice">
              <el-input-number :min="0.1" v-model="form.zz.tenHourPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-text type="info" class="el-remark-text"></el-text>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="周租价格" prop="zz.weekPrice">
              <el-input-number :min="0.1" v-model="form.zz.weekPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-text type="info" class="el-remark-text"></el-text>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" class="cyber-button">确 定</el-button>
          <el-button @click="cancel" class="cyber-button secondary">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AccountInfo">
import {
  listAccountInfo,
  changeStatus,
  changeInfo,
  onOff, onOffList,
  zzChangePriceList,
} from "@/api/custom/hpjy.js";
import {
  parsedJson,
  selectConfirm,
  copyToClipboard,
  isStrEmpty,
  encodeBase64,
  decodeBase64,
  loadAndMergeColumns
} from "@/utils/ruoyi.js";
import {watch} from "vue";
import {
  CircleCheck,
  CircleClose,
  Delete,
  DocumentCopy, Download,
  Edit, EditPen,
  Message,
  Refresh,
  Upload,
  View
} from "@element-plus/icons-vue";
import TableContextMenu from '@/components/TableContextMenu/index.vue'
import RightToolbarStore from '@/components/RightToolbarStore/index.vue'

const {proxy} = getCurrentInstance();

const tableData = ref([]);
// 表格引用
const tableRef = ref(null);
// 当前编辑行的索引
const editingRowZh = ref(null); // 使用账号标识代替行索引
// 原始数据备份（用于编辑取消）
const originalRowData = ref(null);

const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);

const selectedRows = ref([]);
// 展开的行
const expandedRowKeys = ref(new Set());
// 刷新倒计时
const secondsLeft = ref(5);
const single = ref(true);
const multiple = ref(true);

const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const bh_allstatus = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    synZh: "0",

    htype: "0",
    hstatus: undefined,
    wgname: undefined,
    zh: undefined,
    hid: undefined,
  },
  rules: {
    'zz.minTime': [{required: true, message: "起租时长不能为空", trigger: "blur"}],
    'zz.hourPrice': [{required: true, message: "时租价格不能为空", trigger: "blur"}],
    'zz.oneNightPrice': [{required: true, message: "包夜价格不能为空", trigger: "blur"}],
    'zz.tenHourPrice': [{required: true, message: "10小时价不能为空", trigger: "blur"}],
    'zz.dayPrice': [{required: true, message: "天租价格不能为空", trigger: "blur"}],
    'zz.weekPrice': [{required: true, message: "周租价格不能为空", trigger: "blur"}],
    'zz.morningPrice': [{required: true, message: "包早价格不能为空", trigger: "blur"}],
    'zz.afternoonPrice': [{required: true, message: "包午价格不能为空", trigger: "blur"}],
  }
});

const {queryParams, form, rules} = toRefs(data);

const {
  bh_zh_type,
  bh_ydstatus,
  bh_erjpwd,
  bh_jwstatus,
  bh_zhw_zt,
  bh_uhz_zt,
  bh_zz_zt,
  bh_htype,
  bh_common_zt
} = proxy.useDict("bh_zh_type", "bh_ydstatus", "bh_erjpwd", "bh_jwstatus", "bh_zhw_zt", "bh_uhz_zt", "bh_zz_zt", "bh_htype", "bh_common_zt");

// 当前选中行
const selectedRow = ref(null);
// 自定义菜单项 - 支持条件高亮
const customMenuItems = ref([
  {
    label: '查看详情',
    action: 'view',
    icon: markRaw(View),
    highlightCondition: (row) => row.role === '管理员'
  },
  {
    label: '编辑信息',
    action: 'edit',
    icon: markRaw(Edit)
  },
  {
    label: '上架',
    action: 'onShelf',
    icon: markRaw(Upload),
  },
  {
    label: '下架',
    action: 'offShelf',
    icon: markRaw(Download),
  },
  {
    label: '改价',
    action: 'price',
    icon: markRaw(EditPen),
  },
  {
    label: '复制内容',
    action: 'copy',
    icon: markRaw(DocumentCopy)
  },
  // { type: 'divider' },
  // {
  //   label: '删除记录',
  //   action: 'delete',
  //   icon: markRaw(Delete),
  //   highlightCondition: (row) => row.status === 'Inactive'
  // },
  // { type: 'divider' },
  // {
  //   label: '状态操作',
  //   icon: markRaw(CircleCheck),
  //   children: [
  //     {
  //       label: '激活账户',
  //       action: 'activate',
  //       icon: markRaw(CircleCheck),
  //       highlightCondition: (row) => row.status === 'Inactive'
  //     },
  //     {
  //       label: '停用账户',
  //       action: 'deactivate',
  //       icon: markRaw(CircleClose),
  //       highlightCondition: (row) => row.status === 'Active'
  //     }
  //   ]
  // },
  // {
  //   label: '发送邮件',
  //   action: 'email',
  //   icon: markRaw(Message)
  // },
  {
    label: '刷新页面',
    action: 'refresh',
    icon: markRaw(Refresh)
  }
]);

const autoCalcPrice = () => {
  const hourPrice = form.value.zz.hourPrice;
  if (isStrEmpty(hourPrice)) return;

  // 转换为数值类型并保留两位小数
  const hp = Number(hourPrice);

  form.value.zz.dayPrice = +(hp * 14).toFixed(2); // +号将字符串转回数值
  form.value.zz.morningPrice = +(hp * 3).toFixed(2);
  form.value.zz.afternoonPrice = +(hp * 6).toFixed(2);
  form.value.zz.oneNightPrice = +(hp * 5).toFixed(2);
  form.value.zz.tenHourPrice = +(hp * 8).toFixed(2);
  form.value.zz.weekPrice = +(hp * 70).toFixed(2);
}

const handleRowSelected = (row) => {
  selectedRow.value = row;
  console.log(`选中行: ${row.wgname} (ID: ${row.zh})`);
};

// 处理菜单操作
const handleMenuAction = ({action, row}) => {
  let message = '';

  switch (action) {
    case 'view':
      tableRef.value?.toggleRowExpansion(row, true);
      break;
    case 'edit':
      startEditing(row);
      break;
    case 'copy':
      const clipboardData = [`QQ：${row.zh}`];
      if (!isStrEmpty(row.zhw_hid)) clipboardData.push(`租号玩货架：${row.zhw_hid}`)
      if (!isStrEmpty(row.uhz_hid)) clipboardData.push(`U号租货架：${row.uhz_hid}`)
      if (!isStrEmpty(row.zz_hid)) clipboardData.push(`转转货架：${row.zz_hid}`)
      const msg = clipboardData.join("；");
      copyToClipboard(msg);
      break;
    case 'offShelf':
      handleOffShelf(row);
      break;
    case 'onShelf':
      handleOnShelf(row);
      break;
    case 'price':
      changePrice(row);
      break;
      // case 'delete':
      //   message = `删除 ${row.name} 的记录`;
      //   // 实际应用中这里应该调用API删除
      //   tableData.value = tableData.value.filter(item => item.id !== row.id);
      //   console.log(`已删除 ${row.name} 的记录`, 'success');
      //   selectedRow.value = null;
      //   return;
      // case 'activate':
      //   row.status = 'Active';
      //   message = `已激活 ${row.name} 的账户`;
      //   break;
      // case 'deactivate':
      //   row.status = 'Inactive';
      //   message = `已停用 ${row.name} 的账户`;
      //   break;
      // case 'email':
      //   message = `向 ${row.name} (${row.email}) 发送邮件`;
      //   break;
    case 'refresh':
      message = '刷新页面';
      setTimeout(() => location.reload(), 300);
      break;
  }

  console.log(message, 'success');
};

// 高亮当前选中行
const tableRowClassName = (row, currentRow) => {
  if (currentRow && row.zh === currentRow.zh) {
    return 'highlight-row';
  }
  return '';
};

// 定时刷新逻辑
let timer = null;
const startRefreshTimer = () => {
  if (timer) clearInterval(timer);

  timer = setInterval(() => {
    secondsLeft.value--;

    if (secondsLeft.value <= 0) {
      secondsLeft.value = 5;
      fetchData();
    }
  }, 1000);
};
// 开始编辑行
const startEditing = (row) => {
  // 从表格数据中查找当前行
  const currentRow = tableData.value.find(item => item.zh === row.zh);
  if (!currentRow) return;

  // 保存原始数据（深拷贝）
  originalRowData.value = JSON.parse(JSON.stringify(currentRow));
  editingRowZh.value = row.zh;
};

// 保存编辑
const saveEditing = (row) => {
  editingRowZh.value = null;
  originalRowData.value = null;

  changeInfo({"zh": row.zh, "usort": row.usort, "remark": row.remark}).then(() => {
    proxy.$modal.msgSuccess('数据已保存');
    getList();
  }).catch(() => {
  });
};

// 取消编辑
const cancelEditing = () => {
  if (editingRowZh.value && originalRowData.value) {
    const index = tableData.value.findIndex(item => item.zh === editingRowZh.value);
    if (index !== -1) {
      Object.assign(tableData.value[index], originalRowData.value);
    }
  }
  editingRowZh.value = null;
  originalRowData.value = null;
};

const fetchData = async () => {
  // 保存当前编辑状态
  const currentEditingZh = editingRowZh.value;
  const currentEditingData = originalRowData.value;

  // 保存当前展开行
  const currentExpandedRows = [...expandedRowKeys.value];

  // 保存当前选中行
  const currentSelectedRows = [...selectedRows.value];

  // 保存用户当前编辑的值
  let userEditingData = null;
  if (currentEditingZh) {
    const editingRow = tableData.value.find(item => item.zh === currentEditingZh);
    if (editingRow) {
      userEditingData = {
        usort: editingRow.usort,
        remark: editingRow.remark
      };
    }
  }

  try {
    const response = await listAccountInfo(proxy.addDateRange(queryParams.value, dateRange.value));
    const newData = response.rows;

    // 创建现有数据的映射
    const existingDataMap = new Map(tableData.value.map(item => [item.zh, item]));

    // 处理新数据
    newData.forEach(newItem => {
      const existingItem = existingDataMap.get(newItem.zh);

      if (existingItem) {
        // 如果是正在编辑的行，保留用户编辑的值
        if (currentEditingZh === newItem.zh && userEditingData) {
          // 只更新非编辑字段
          Object.keys(newItem).forEach(key => {
            if (key !== 'usort' && key !== 'remark') {
              existingItem[key] = newItem[key];
            }
          });

          // 恢复用户编辑的值
          existingItem.usort = userEditingData.usort;
          existingItem.remark = userEditingData.remark;
        } else {
          // 其他行直接更新
          Object.assign(existingItem, newItem);
        }
      } else {
        // 添加新数据
        tableData.value.push(newItem);
      }
    });

    // 移除已删除的数据
    const newIds = new Set(newData.map(item => item.zh));
    tableData.value = tableData.value.filter(item => newIds.has(item.zh));

    // 恢复之前展开的行
    nextTick(() => {
      // 清空所有展开状态
      tableRef.value?.toggleRowExpansion(null, false);

      // 只展开那些确实在 expandedRows 中的行
      currentExpandedRows.forEach(rowZh => {
        const targetRow = tableData.value.find(item => item.zh === rowZh);
        if (targetRow) {
          tableRef.value?.toggleRowExpansion(targetRow, true);
        }
      });
    });

    // 恢复编辑状态
    if (currentEditingZh) {
      const targetRow = tableData.value.find(item => item.zh === currentEditingZh);
      if (targetRow) {
        // 确保编辑状态保持
        editingRowZh.value = currentEditingZh;

        // 如果用户编辑过数据，恢复用户编辑的值
        if (userEditingData) {
          targetRow.usort = userEditingData.usort;
          targetRow.remark = userEditingData.remark;
        }
      } else {
        // 如果行被删除，清除编辑状态
        editingRowZh.value = null;
        originalRowData.value = null;
      }
    }

    // 恢复选中行 - 通过调用 handleSelectionChange 保持数据结构一致
    const selectedZhSet = new Set(currentSelectedRows.map(row => row.zh));
    const restoredSelection = tableData.value.filter(item => selectedZhSet.has(item.zh));

    // 使用 nextTick 确保 DOM 更新完成后再恢复选中状态
    nextTick(() => {
      // 先清空选中状态
      tableRef.value?.clearSelection();

      // 恢复选中状态
      restoredSelection.forEach(row => {
        tableRef.value?.toggleRowSelection(row, true);
      });

      // 此时表格的 selection-change 事件会触发 handleSelectionChange
      // 从而自动更新 selectedRows 的格式
    });

    // 更新总数
    total.value = response.total;

    // 更新按钮状态
    single.value = selectedRows.value.length !== 1;
    multiple.value = !selectedRows.value.length;

  } catch (error) {
    console.error('无感刷新失败:', error);
    //proxy.$modal.msgError('无感刷新失败');
  } finally {
    loading.value = false;
  }
};


/** 自动生成-查询列表 */
function getList(synZh) {
  synZh=typeof synZh!='string'?'':synZh;
  cancelEditing();
  loading.value = true;
  console.log(queryParams.value,synZh)
  listAccountInfo(proxy.addDateRange(queryParams.value, dateRange.value), synZh).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
  }).finally(() => {
    loading.value = false
    secondsLeft.value = 5;
  });
}

/** 自动生成-取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 自动生成-表单重置 */
function reset() {
  form.value = {
    channel: undefined,
    zhlist: [],
    zz: {},
  };
  proxy.resetForm("cinfoForm");
}

/** 自动生成-搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 自动生成-重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 自动生成-多选框选中数据 */
function handleSelectionChange(selection) {
  selectedRows.value = selection.map(item => ({"zh": item.zh, "zhCfg": encodeBase64(item.zh_cfg)}));
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 处理展开行变化
const handleExpandChange = (row, expanded) => {
  expandedRowKeys.value = new Set();
  if (expanded.length > 0) {
    expanded.forEach(item => {
      expandedRowKeys.value.add(item.zh);
    });
  }
};

function channelOptionList(row) {
  const channelOptions = [...bh_htype.value];
  console.log(row)
  // 将 row 统一转换为数组处理
  const rowArray = Array.isArray(row) ? row : [row];

  // 收集所有已存在的渠道值
  const existSet = new Set();
  rowArray.forEach(item => {
    let zhCfg = {}; // 初始化空对象，避免后续处理 undefined

    // 获取配置数据
    const cfgData = Array.isArray(row) ? item.zhCfg : item.zh_cfg;

    if (Array.isArray(row) && !isStrEmpty(cfgData)) {
      // 当 row 是数组时，进行 Base64 解码（前提是 cfgData 不为空）
      try {
        zhCfg = JSON.parse(decodeBase64(cfgData));
      } catch (error) {
        console.error('Base64解码或JSON解析失败:', error);
        // 解码失败时保持 zhCfg 为空对象
      }
    } else if (!isStrEmpty(cfgData)) {
      // 当 row 是单个对象时，直接解析 JSON 字符串
      try {
        zhCfg = JSON.parse(cfgData);
      } catch (error) {
        console.error('JSON解析失败:', error);
        // 解析失败时保持 zhCfg 为空对象
      }
    }

    // 收集渠道值
    if (!isStrEmpty(zhCfg.hid)) existSet.add("1");
    if (!isStrEmpty(zhCfg.zuHid)) existSet.add("2");
    if (!isStrEmpty(zhCfg.infoId)) existSet.add("3");
  });

  // 过滤渠道选项
  let filteredOptions = channelOptions.filter(option => existSet.has(option.value));

  // 当 existSet 长度 >1 时，额外保留 value=0 的选项
  if (existSet.size > 1) {
    const allOption = channelOptions.find(option => option.value === "0");
    if (allOption && !existSet.has("0")) {
      filteredOptions = [allOption, ...filteredOptions];
    }
  }

  return filteredOptions;
}

/** 自动生成-提交 */
function submitForm() {
  proxy.$refs["cinfoForm"].validate(valid => {
    if (valid) {
      zzChangePriceList(form.value).then(response => {
        proxy.$modal.msgSuccess("操作已完成");
        open.value = false;
      }).finally(()=>getList("1"));
    }
  });
}

const channelName = (channel) => {
  const htype = channel || queryParams.value.htype;
  // 筛选出匹配的项
  const matched = bh_htype.value.find(item => item.value == htype);
  // 如果找到则返回label，否则返回空字符串或默认值
  return matched ? matched.label : '';
}

watch(() => queryParams.value.htype, (newVal, oldVal) => {
  if (newVal == "1") {
    bh_allstatus.value = bh_zhw_zt.value;
  } else if (newVal == "2") {
    bh_allstatus.value = bh_uhz_zt.value;
  } else if (newVal == "3") {
    bh_allstatus.value = bh_zz_zt.value;
  } else {
    bh_allstatus.value = bh_common_zt.value;
  }
}, {
  immediate: true,
  deep: false
})

watch(bh_common_zt, (newVal) => {
  if (Array.isArray(newVal) && newVal.length > 0) {
    bh_allstatus.value = bh_common_zt.value;
  }
}, {immediate: true});

/** 上架 */
function handleOnShelf(row) {
  // 定义渠道选项
  const channelOptions = channelOptionList(row);

  selectConfirm({
    title: '确认上架',
    message: `请选择上架渠道，涉及账号：[${row.zh}]`,
    options: channelOptions,
    placeholder: '请选择渠道'
  })
      .then(selectedChannel => {
        const data = {
          "onOff": "1",
          "channel": selectedChannel,
          "zh": row.zh,
          "zhCfg": encodeBase64(row.zh_cfg)
        };

        return onOff(data);
      })
      .then(() => {
        proxy.$modal.msgSuccess("操作已完成");
      })
      .catch(error => {
        if (error.message !== 'cancel') {
          // proxy.$modal.msgError(error.message);
        }
      }).finally(() => getList("1"));
}

/** 下架 */
function handleOffShelf(row) {
  // 定义渠道选项
  const channelOptions = channelOptionList(row);

  selectConfirm({
    title: '确认下架',
    message: `请选择下架渠道，涉及账号：[${row.zh}]`,
    options: channelOptions,
    placeholder: '请选择渠道'
  })
      .then(selectedChannel => {
        const data = {
          "onOff": "2",
          "channel": selectedChannel,
          "zh": row.zh,
          "zhCfg": encodeBase64(row.zh_cfg)
        };

        return onOff(data);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("操作已完成");
      })
      .catch(error => {
        if (error.message !== 'cancel') {
          // proxy.$modal.msgError(error.message);
        }
      }).finally(() => getList("1"));
}

/** 上架 */
function handleOnShelfList() {
  const zhs = selectedRows.value.map(item => item.zh);
  // 定义渠道选项
  const channelOptions = channelOptionList(selectedRows.value);

  selectConfirm({
    title: '确认上架',
    message: `请选择上架渠道，涉及账号：${zhs}`,
    options: channelOptions,
    placeholder: '请选择渠道'
  })
      .then(selectedChannel => {
        const data = {
          "onOff": "1",
          "channel": selectedChannel,
          "zhlist": selectedRows.value
        };

        return onOffList(data);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("操作已完成");
      })
      .catch(error => {
        if (error.message !== 'cancel') {
          // proxy.$modal.msgError(error.message);
        }
      }).finally(() => getList("1"));
}

/** 下架 */
function handleOffShelfList() {
  const zhs = selectedRows.value.map(item => item.zh);
  // 定义渠道选项
  const channelOptions = channelOptionList(selectedRows.value);

  selectConfirm({
    title: '确认下架',
    message: `请选择下架渠道，涉及账号：${zhs}`,
    options: channelOptions,
    placeholder: '请选择渠道'
  })
      .then(selectedChannel => {
        const data = {
          "onOff": "2",
          "channel": selectedChannel,
          "zhlist": selectedRows.value
        };

        return onOffList(data);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("操作已完成");
      })
      .catch(error => {
        if (error.message !== 'cancel') {
          // proxy.$modal.msgError(error.message);
        }
      }).finally(() => getList("1"));
}

/** 改价 */
function changePrice(row) {
  // 定义渠道选项
  const channelOptions = channelOptionList(row);

  selectConfirm({
    title: '改价',
    message: `请选择改价渠道，涉及账号：[${row.zh}]`,
    options: channelOptions,
    placeholder: '请选择渠道'
  })
      .then(selectedChannel => {
        btnChangePrice(selectedChannel,row)
      })
      .catch(error => {
        if (error.message !== 'cancel') {
          // proxy.$modal.msgError(error.message);
        }
      });
}

function btnChangePrice(channel,row) {
  reset();
  open.value = true;
  title.value = `改价-QQ：${row.zh}；渠道：${channelName( channel)}`;
  form.value = {
    "channel": channel,
    "zhlist":[{
      "zh": row.zh,
      "zhCfg": encodeBase64(row.zh_cfg)
    }],
    "zz":{}
  };
}

function btnChangePriceList(channel,zhs) {
  reset();
  open.value = true;
  title.value = `批量改价；渠道：${channelName( channel)}`;
  form.value = {
    "channel": channel,
    "zhlist":zhs,
    "zz":{}
  };
}

/** 改价 */
function changePriceList() {
  const zhs = selectedRows.value.map(item => item.zh);
  // 定义渠道选项
  const channelOptions = channelOptionList(selectedRows.value);

  selectConfirm({
    title: '批量改价',
    message: `请选择批量改价渠道，涉及账号：${zhs}`,
    options: channelOptions,
    placeholder: '请选择渠道'
  })
      .then(selectedChannel => {
        btnChangePriceList(selectedChannel,selectedRows.value)
      })
      .catch(error => {
        if (error.message !== 'cancel') {
          // proxy.$modal.msgError(error.message);
        }
      });
}

/** 自动生成-状态修改  */
function handleStatusChange(row) {
  secondsLeft.value = 5;
  changeStatus({"zh": row.zh, "offOn": row.off_on}).then(response => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).finally(() => {
  });
};

getList();

const columns = ref([
  {key: 0, label: `租号玩`, visible: true},
  {key: 1, label: `U号租`, visible: true},
  {key: 2, label: `转转`, visible: true},
]);

// 监听 columns 变化并持久化
watch(
    () => columns.value,
    (newColumns) => {
      try {
        localStorage.setItem('hpjy_columns_key', JSON.stringify(newColumns));
      } catch (error) {
        console.error('Failed to save columns to localStorage:', error);
      }
    },
    {deep: true}
);

// 生命周期钩子
onMounted(() => {
  columns.value = loadAndMergeColumns("hpjy_columns_key", columns.value)
  fetchData();
  startRefreshTimer();
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>

<style scoped>
.cyberpunk-theme {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
  min-height: 100vh;
  padding: 20px;
  position: relative;
  color: #333;
}

.cyberpunk-theme::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 10% 20%, rgba(122, 122, 222, 0.05) 0%, transparent 20%),
    radial-gradient(circle at 90% 80%, rgba(122, 222, 122, 0.05) 0%, transparent 20%);
  z-index: -1;
}

/* 表单美化 */
.cyber-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #409eff;
}

/* 按钮美化 */
.cyber-button {
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  font-weight: 500;
  border: 1px solid transparent;
}

.cyber-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: 0.5s;
}

.cyber-button:hover::before {
  left: 100%;
}

.cyber-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.cyber-button.secondary {
  background: #f4f4f5;
  border-color: #dcdfe6;
  color: #606266;
}

.cyber-button.secondary:hover {
  background: #e9e9eb;
  border-color: #c0c4cc;
  color: #606266;
  box-shadow: 0 4px 12px rgba(128, 128, 128, 0.2);
}

.cyber-button.action {
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.cyber-button.action:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.cyber-button.calc {
  border-radius: 6px;
  background: #67c23a;
  border-color: #67c23a;
  color: white;
}

.cyber-button.calc:hover {
  background: #85ce61;
  border-color: #85ce61;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.cyber-button-icon {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 6px;
  padding: 4px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5;
}

.cyber-actions {
  background: white;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

/* 表格美化 */
.cyber-table {
  background: white !important;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
}

.cyber-table :deep(.el-table__header th) {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

.cyber-table :deep(.el-table__body td) {
  border-bottom: 1px solid #ebeef5;
}

.cyber-table :deep(.el-table__body tr:hover) {
  background: #f5f7fa;
}

.cyber-table :deep(.el-table__body tr.highlight-row) {
  background: #ecf5ff;
}

.cyber-expand {
  background: #f8fafc !important;
  border-radius: 8px;
  margin: 0px 1px;
  border: 1px solid #ebeef5;
}

.cyber-expand p {
  color: #606266;
}

/* 表格内容美化 */
.table-subtitle {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.equip-item {
  font-size: 13px;
  margin: 2px 0;
}

.equip-item.pink {
  color: #E65D6E;
}

.equip-item.red {
  color: #F56C6C;
}

.platform-header {
  color: #409eff;
  font-weight: 600;
}

.platform-info {
  background: #f5f7fa;
  border-radius: 6px;
  padding: 8px;
  font-size: 13px;
}

.platform-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.platform-price {
  font-weight: 600;
  color: #67c23a;
}

/* 开关美化 */
.cyber-switch :deep(.el-switch__core) {
  border: 1px solid #dcdfe6;
}

.cyber-switch :deep(.el-switch.is-checked .el-switch__core) {
  background: #409eff;
  border-color: #409eff;
}

/* 标签美化 */
.cyber-tag :deep(.el-tag) {
  border-radius: 6px;
}

/* 对话框美化 */
.cyber-dialog :deep(.el-dialog) {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.15);
}

.cyber-dialog :deep(.el-dialog__header) {
  background: #f5f7fa;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.cyber-dialog :deep(.el-dialog__title) {
  color: #606266;
  font-weight: 600;
}

.cyber-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #909399;
}

.cyber-dialog :deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  color: #409eff;
}

/* 分页美化 */
.hpjy-pagination-container {
  background: white;
  border-radius: 10px;
  padding: 15px;
  margin-top: 20px;
/*  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;*/
}

.hpjy-pagination-container :deep(.el-pagination) {
  color: #606266;
}

.hpjy-pagination-container :deep(.el-pagination button) {
  background: white;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
}

.hpjy-pagination-container :deep(.el-pagination button:hover) {
  color: #409eff;
  border-color: #409eff;
}

.hpjy-pagination-container :deep(.el-pager li) {
  background: white;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
}

.hpjy-pagination-container :deep(.el-pager li.active) {
  background: #409eff;
  border-color: #409eff;
  color: white;
}

/* 原有样式保持不变 */
.remark-container {
  position: relative;
  min-height: 40px;
  padding: 5px;
}

.el-remark-text{
  display: inline-flex;
  line-height: 32px;
}

:deep(.el-table__body-wrapper) {
  overflow: visible;
}

:deep(.el-table__body tr) {
  position: relative;
}

:deep(.el-table__body .remark-column .cell) {
  overflow: visible !important;
}

:deep(.el-table .highlight-row) {
  background-color: #ecf5ff !important;
}
</style>